package com.huanletao.okhttp;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;


import java.util.logging.Level;
import java.util.logging.Logger;

public class OkHttpExample {
    private static final Logger LOGGER = Logger.getLogger(OkHttpExample.class.getName());
    private static final OkHttpClient client = new OkHttpClient();
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 同步 GET 请求示例
     * @param url 请求的 URL
     * @return 响应结果，请求失败时返回 null
     */
    public static String syncGet(String url) {
        Request request = new Request.Builder()
               .url(url)
               .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                return response.body().string();
            }
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "同步 GET 请求出错", e);
        }
        return null;
    }

    /**
     * 异步 GET 请求示例
     * @param url 请求的 URL
     * @param callback 回调接口，处理请求结果
     */
    public static void asyncGet(String url, Callback callback) {
        Request request = new Request.Builder()
               .url(url)
               .build();

        client.newCall(request).enqueue(callback);
    }

    /**
     * 同步 POST JSON 请求示例
     * @param url 请求的 URL
     * @param json 请求的 JSON 数据
     * @return 响应结果，请求失败时返回 null
     */
    public static String syncPostJson(String url, String json) {
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
               .url(url)
               .post(body)
               .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                return response.body().string();
            }
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "同步 POST JSON 请求出错", e);
        }
        return null;
    }

    /**
     * 异步 POST JSON 请求示例
     * @param url 请求的 URL
     * @param json 请求的 JSON 数据
     * @param callback 回调接口，处理请求结果
     */
    public static void asyncPostJson(String url, String json, Callback callback) {
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
               .url(url)
               .post(body)
               .build();

        client.newCall(request).enqueue(callback);
    }

    public static void main(String[] args) {
        // 同步 GET 请求示例
        String syncGetResponse = syncGet("https://jsonplaceholder.typicode.com/todos/1");
        System.out.println("同步 GET 请求响应: " + syncGetResponse);

        // 异步 GET 请求示例
        asyncGet("https://jsonplaceholder.typicode.com/todos/1", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LOGGER.log(Level.SEVERE, "异步 GET 请求失败", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    if (response.isSuccessful() && responseBody != null) {
                        System.out.println("异步 GET 请求响应: " + responseBody.string());
                    }
                }
            }
        });

        // 准备 POST 的 JSON 数据
        Map<String, String> data = new HashMap<>();
        data.put("title", "foo");
        data.put("body", "bar");
        data.put("userId", "1");
        String json = null;
        try {
            json = objectMapper.writeValueAsString(data);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "转换 JSON 数据出错", e);
        }

        if (json != null) {
            // 同步 POST JSON 请求示例
            String syncPostJsonResponse = syncPostJson("https://jsonplaceholder.typicode.com/posts", json);
            System.out.println("同步 POST JSON 请求响应: " + syncPostJsonResponse);

            // 异步 POST JSON 请求示例
            asyncPostJson("https://jsonplaceholder.typicode.com/posts", json, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    LOGGER.log(Level.SEVERE, "异步 POST JSON 请求失败", e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try (ResponseBody responseBody = response.body()) {
                        if (response.isSuccessful() && responseBody != null) {
                            System.out.println("异步 POST JSON 请求响应: " + responseBody.string());
                        }
                    }
                }
            });
        }
    }
}

